#%%
import numpy as np
import matplotlib.pyplot as plt

class PointD:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __add__(self, other):
        if isinstance(other, PointD):
            return PointD(self.x + other.x, self.y + other.y)
        return PointD(self.x + other, self.y + other)

    def __mul__(self, other):
        if isinstance(other, (int, float)):
            return PointD(self.x * other, self.y * other)
        raise TypeError("Unsupported operand type(s) for *: 'PointD' and '{}'".format(type(other)))

    def __repr__(self):
        return f"PointD({self.x}, {self.y})"

def chaikin_smoothing(points, tension=0.5, nr_of_iterations=3):
    if len(points) < 3:
        return points
    if nr_of_iterations < 1:
        nr_of_iterations = 1
    if tension < 0:
        tension = 0
    elif tension > 1:
        tension = 1

    cut_dist = 0.05 + (tension * 0.4)
    for _ in range(nr_of_iterations):
        new_points = [points[0]]
        for i in range(len(points) - 1):
            p0 = points[i]
            p1 = points[i + 1]
            q = PointD((1 - cut_dist) * p0.x + cut_dist * p1.x, (1 - cut_dist) * p0.y + cut_dist * p1.y)
            r = PointD(cut_dist * p0.x + (1 - cut_dist) * p1.x, cut_dist * p0.y + (1 - cut_dist) * p1.y)
            new_points.append(q)
            new_points.append(r)
        new_points.append(points[-1])
        points = new_points
    return points
def _main_():
#%%
    # Example usage
    points = [PointD(0, 0), PointD(3, 2), PointD(2, 0), PointD(4, 0), PointD(5, 1), PointD(6, 0)]
    smoothed_points = chaikin_smoothing(points, tension=0.5, nr_of_iterations=3)

    # Convert to numpy arrays for plotting
    smoothed_x = [p.x for p in smoothed_points]
    smoothed_y = [p.y for p in smoothed_points]

    # Plot the original points and the smoothed curve
    plt.figure(figsize=(10, 6))
    plt.plot([p.x for p in points], [p.y for p in points], 'o-', label='原始点')
    plt.plot(smoothed_x, smoothed_y, '-', label='Chaikin Smoothing')
    plt.legend()
    plt.title('Chaikin Smoothing')
    plt.show()
# %%
